package com.guomei.service.curse.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guomei.bean.User;
import com.guomei.bean.curse.*;
import com.guomei.mapper.UserMapper;
import com.guomei.mapper.curse.CourseCategoryMapper;
import com.guomei.mapper.curse.CourseCategoryRelationMapper;
import com.guomei.mapper.curse.CourseMapper;
import com.guomei.service.curse.CourseCategoryService;
import com.guomei.utils.PageData;
import com.guomei.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 课程类别表服务实现类
 */
@Service
@Slf4j
@Transactional
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Resource
    private CourseCategoryMapper courseCategoryMapper;
    @Resource
    private CourseCategoryRelationMapper relationMapper;
    @Resource
    private CourseMapper courseMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public int addCourseCategory(CourseCategory courseCategory) {
        return courseCategoryMapper.insert(courseCategory);
    }

    @Override
    @Transactional
    public int deleteCourseCategoryById(Long id) {
        int i = relationMapper.deleteByCategoryId(id);
        return courseCategoryMapper.deleteById(id);
    }

    @Override
    @Transactional
    public int updateCourseCategory(CourseCategory courseCategory) {
        return courseCategoryMapper.update(courseCategory);
    }

    @Override
    public CourseCategory getCourseCategoryById(Long id) {
        return courseCategoryMapper.selectById(id);
    }

    @Override
    public List<CourseCategory> getAllCourseCategories() {
        return courseCategoryMapper.selectAll();
    }

    @Override
    public List<CourseCategory> getCourseCategoriesByParentId(Long parentId) {
        return courseCategoryMapper.selectByParentId(parentId);
    }

    @Override
    public List<CourseCategory> getCourseCategoriesByStatus(Integer status) {
        return courseCategoryMapper.selectByStatus(status);
    }

    @Override
    public Result<?> selectByCondition(CourseCategory courseCategory) {
        PageHelper.startPage(courseCategory.getPageNum(), courseCategory.getPageSize());
        List<CourseCategory> courseCategories = courseCategoryMapper.selectByCondition(courseCategory);
        // 封装分页结果到PageData
        PageData<CourseCategory> pageData = new PageData<>();
        PageInfo<CourseCategory> pageInfo = new PageInfo<>(courseCategories);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(courseCategory.getPageNum());
        pageData.setPageSize(courseCategory.getPageSize());
        return Result.success(pageData);
    }

    @Override
    public Result<?> byCategoryGetAll(ByCategoryGetAllDTO byCategoryGetAllDTO) {
        ArrayList<ByCategoryGetAllResponse> ByCategoryGetAllResponse = new ArrayList<>();
        ArrayList<Long> courseIds = new ArrayList<>();
        if (byCategoryGetAllDTO.getCategoryIds() == null) {
            return Result.fail("缺少类别id");
        }
        for (Long categoryId : byCategoryGetAllDTO.getCategoryIds()) {
            ByCategoryGetAllResponse byCategoryGetAllResponse = new ByCategoryGetAllResponse();
            CourseCategoryRelation courseCategoryRelation = new CourseCategoryRelation();
            courseCategoryRelation.setCategoryId(categoryId);
            //获取所有课程id
            List<CourseCategoryRelation> courseCategoryRelations = relationMapper.selectByCondition(courseCategoryRelation);
            if (courseCategoryRelations != null && !courseCategoryRelations.isEmpty()){

                for (CourseCategoryRelation relation : courseCategoryRelations) {
                    courseIds.add(relation.getCourseId());
                }
                List<Course> courses = courseMapper.selectByIds(courseIds);
                if (courses != null && !courses.isEmpty()){
                    for (Course cours : courses) {
                        User user = userMapper.selectById(cours.getTeacherId());
                        cours.setTeacher(user);
                    }
                    byCategoryGetAllResponse.setCategoryId(categoryId);
                    byCategoryGetAllResponse.setCourses(courses);
                    ByCategoryGetAllResponse.add(byCategoryGetAllResponse);
                } else {
                    byCategoryGetAllResponse.setCategoryId(categoryId);
                    ByCategoryGetAllResponse.add(byCategoryGetAllResponse);
                    log.info("{}类别id下有课程信息，但是课程查询不到老师信息", categoryId);
                    continue;
                }
                courseIds.clear();
            } else {
                byCategoryGetAllResponse.setCategoryId(categoryId);
                ByCategoryGetAllResponse.add(byCategoryGetAllResponse);
                log.info("{}类别id下无课程信息", categoryId);
                continue;
            }
        }
        return Result.success(ByCategoryGetAllResponse);
    }

//    @Override
//    public List<CourseCategory> getCategoriesWithCoursesByIds(List<Long> categoryIds) {
//        if (categoryIds == null || categoryIds.isEmpty()) {
//            log.warn("categoryIds为空，返回空列表");
//            return new ArrayList<>();
//        }
//
//        log.info("开始查询分类及其课程，categoryIds: {}", categoryIds);
//        List<CourseCategory> categories = courseCategoryMapper.selectCategoriesWithCoursesByIds(categoryIds);
//        log.info("查询完成，返回分类数量: {}", categories.size());
//
//        // 处理课程列表，过滤掉null课程对象
//        for (CourseCategory category : categories) {
//            if (category.getCourses() != null) {
//                // 过滤掉id为null的空课程对象
//                List<Course> validCourses = category.getCourses().stream()
//                    .filter(course -> course.getId() != null)
//                    .collect(Collectors.toList());
//                category.setCourses(validCourses);
//                log.info("分类 {} 包含有效课程数量: {}", category.getId(), validCourses.size());
//            } else {
//                category.se tCourses(new ArrayList<>());
//                log.info("分类 {} 没有课程，设置为空列表", category.getId());
//            }
//        }
//
//        return categories;
//    }

}
